<template>
    <div class="chat-main flex fill">
        <chatHistory class="chat-history" @newConversationClick="newConversationClick"
            @conversationClick="conversationClick"></chatHistory>
        <div class="chat-conversation  flex-1 columnStartCenter">
            <div class="chat-conversation-top rowBetweenStretch">
                <el-select v-model="modelType" style="width: 200px;" v-if="false">
                    <el-option label="本地部署Ollama" value="OLLAMA_CHAT_MODEL"></el-option>
                    <el-option label="其他模型" value="other"></el-option>
                </el-select>

                <div>上传知识库占位置</div>
            </div>
            <div class="chat-conversation-main columnStartCenter   scrollbar-style">
                <div class="chat-conversation-message">
                    <div v-for="(item, index) in messageList" :key="index" :class="getMessageClass(item)">
                        <div v-if="item.messageType === 'ASSISTANT'" class="assistant-message">

                            <div class="thinkMessage" v-if="item.thinkMessage">
                                <div class="rowBetweenStart">
                                    <div v-if="item.isThink">正在深度思考</div>
                                    <div v-else>以完成深度思考</div>
                                    <el-button v-if="item.isOpenThink == true" type="text" :icon="ArrowDown"
                                        @click="item.isOpenThink = false"> </el-button>
                                    <el-button v-else type="text" :icon="ArrowUp" @click="item.isOpenThink = true">
                                    </el-button>
                                </div>
                                <p v-if="item.isOpenThink" v-html="item.thinkMessage"></p>
                            </div>

                            <p v-html="md.render(item.message)"></p>
                        </div>

                        <div v-else class="user-message">
                            <p v-html="item.message"></p>
                        </div>
                    </div>
                </div>

            </div>
            <div class="chat-conversation-input columnStartStretch">
                <!-- <a-select v-model:value="selectTool" class="h100">
                    <a-select-option value="tool1">工具1</a-select-option>
                </a-select> -->
                <el-input class="scrollbar-style" input-style="box-shadow: none;" autofocus="true" resize="none"
                    @keyup.enter.native="sendMessageClick()" v-model="userMessage" placeholder="问我我都会"
                    :autosize="{ minRows: 1, maxRows: 4 }" type="textarea">
                </el-input>
                <div class="rowBetweenStretch">
                    <div></div>
                    <div>
                        <el-button type="primary" @click="openUploadDia()">上传文件</el-button>
                        <el-button type="primary" @click="sendMessageClick()">发送</el-button>
                    </div>
                </div>
            </div>

        </div>
        <uploadDia ref="uploadDia"></uploadDia>
    </div>
</template>

<script setup lang="ts">
import chatHistory from "./components/chatHistory.vue"

import uploadDia from "./components/uploadDia.vue"
import { ref, onMounted, watch, computed, nextTick, onUpdated } from 'vue'
import { chatStream } from "./api/chatClient"
import { newConversation, getChatConversation } from './api/chatClient'
import { useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark-reasonable.css' // 你可以替换成其他主题
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'



const router = useRouter()

interface ChatMessage {
    message: string,
    messageType: string,
    thinkMessage?: string
    isThink?: boolean
    isOpenThink?: boolean

}
let messageList = ref<ChatMessage[]>([]);


let userMessage = ref("");

let modelType = ref("OLLAMA_CHAT_MODEL")

let selectTool = ref("tool1")


let currentConversationId = ref(router.currentRoute.value.query.conversationId as string || "")


const md = new MarkdownIt(
    {
        html: false, // 禁止原始 HTML
        linkify: true, // 自动识别链接
        breaks: true, // 换行符转为 <br>
        highlight(code, lang) {
            if (lang && hljs.getLanguage(lang)) {
                return `<pre class="hljs"><code>${hljs.highlight(code, { language: lang }).value}</code></pre>`;
            }
            return `<pre class="hljs"><code>${md.utils.escapeHtml(code)}</code></pre>`;
        }
    }
)





function addCopyButtons() {
    nextTick(() => {
        document.querySelectorAll('pre code').forEach((block) => {
            if (block.parentElement?.querySelector('.copy-btn')) return; // 避免重复添加

            const btn = document.createElement('button');
            btn.className = 'copy-btn';
            btn.innerText = '复制';
            btn.addEventListener('click', () => {
                navigator.clipboard.writeText(block.textContent || '').then(() => {
                    btn.innerText = '已复制';
                    setTimeout(() => btn.innerText = '复制', 1000);
                });
            });

            block.parentElement?.appendChild(btn);
        });
    });
}

function sendMessageClick() {
    messageList.value.push({
        message: userMessage.value,
        messageType: "USER",
    })
    messageList.value.push({
        message: "",
        messageType: "ASSISTANT",
        thinkMessage: "",
        isOpenThink: true,
        isThink: true
    })
    scrollToBottom()
    chatStream({
        modelType: modelType.value,
        message: userMessage.value,
        conversationId: currentConversationId.value
    }, (conversationId) => {
        userMessage.value = "";
        router.push({
            path: '/',
            query: {
                conversationId: conversationId
            }
        })
    }, (message) => {
        let lastMessage = messageList.value[messageList.value.length - 1];
        lastMessage.message = lastMessage.message + message;
        lastMessage.isThink = false;
        scrollToBottom()

    },
        (thinkMessage) => {
            let lastMessage = messageList.value[messageList.value.length - 1];
            lastMessage.thinkMessage = lastMessage.thinkMessage + thinkMessage;
            lastMessage.isThink = true;
            scrollToBottom()
        },
        () => {
            console.log("思考完成")
        },
        (err) => {

        })

}

function initConversation() {
    messageList.value = [];
    userMessage.value = ""
    if (currentConversationId.value) {
        getChatConversation(currentConversationId.value).then(res => {
            messageList.value = res.data?.messages || []
            scrollToBottom()
        })

    }
}

function scrollToBottom() {
    nextTick(() => {
        const el = document.querySelector('.chat-conversation-main')
        if (el) el.scrollTop = el.scrollHeight
    })
}

function newConversationClick() {
    router.push({
        path: '/',
        query: {
        }
    })
    currentConversationId.value = "";
    initConversation();

}

function conversationClick(conversationId: string) {
    router.push({
        path: '/',
        query: {
            conversationId: conversationId
        }
    })
    currentConversationId.value = conversationId;
    initConversation();
}



function getMessageClass(item: ChatMessage): string {
    if (item.messageType === 'USER') {
        return "chat-conversation-message-item rowEndStretch"
    } else {
        return "chat-conversation-message-item rowStartStretch"
    }
}


function openUploadDia() {
    ref('uploadDia').value.openDia();
}


onMounted(() => {
    initConversation();
})



// 每次 messageList 变动后自动加按钮
watch(messageList, () => {
    addCopyButtons()
})




</script>

<style lang="scss">
.chat-main {
    background-color: rgb(247, 248, 252);;

    .chat-history {
        width: 380px;
    }

    .chat-conversation {
        width: 100%;
        height: 100%;

        .chat-conversation-top {
            display: flex;
            width: 100%;
            height: 60px;
            padding: 20px;
            border-bottom: 1px solid #fff;
        }

        .chat-conversation-main {
            width: 100%;
            height: 100%;
            overflow: auto;


            .chat-conversation-message {
                width: 80%;

                .chat-conversation-message-item {
                    width: 100%;

                    .assistant-message {
                        background-color: #e9e9e980;
                        line-height: 24px;
                        padding: 16px 20px;
                        border-radius: 16px;
                        margin: 12px 0;
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
                        width: 100%;

                        .thinkMessage {
                            color: #8f91a8 !important;

                            p {
                                padding: 0 20px;
                                border-left: 1px solid #e0e0e0;


                            }
                        }
                    }

                    .user-message {
                        background-color: #e9e9e980;
                        line-height: 24px;
                        padding: 16px 20px;
                        border-radius: 16px;
                        margin: 12px 0;
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
                        width: fit-content;
                    }
                }


            }


        }

        .chat-conversation-input {
            width: 80%;
            margin: 20px 0;
            gap: 12px;
            padding: 10px;
            background: #ffffff;
            border-radius: 16px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }


    }
}
</style>